package org.hiucung.lib_base.helper

import android.content.Context
import android.graphics.PixelFormat
import android.os.Build
import android.view.Gravity
import android.view.View
import android.view.WindowManager

/**
 * @title: WindowHelper
 * @projectName OrangeAiVoiceApp
 * @description:窗口帮助类
 * @author Kicc
 * @date 2021/11/29 15:51
 */
object WindowHelper {
    private lateinit var mContext: Context
    private lateinit var mWindowManager: WindowManager
    private lateinit var mLayoutParams: WindowManager.LayoutParams

    fun initHelper(mContext: Context) {
        this.mContext = mContext
        mWindowManager = mContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        mLayoutParams = createLayoutParams()
    }

    /**
     * 创建布局属性，宽高
     */
    private fun createLayoutParams(): WindowManager.LayoutParams {
        val layoutParams = WindowManager.LayoutParams()
        layoutParams.apply {
            this.width = WindowManager.LayoutParams.MATCH_PARENT
            this.height = WindowManager.LayoutParams.MATCH_PARENT
            gravity = Gravity.CENTER
            format = PixelFormat.TRANSLUCENT
            flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
                    WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
            type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            } else {
                WindowManager.LayoutParams.TYPE_PHONE
            }
        }
        return layoutParams
    }

    //获取view
    fun getView(layoutId: Int): View {
        return View.inflate(mContext, layoutId, null)
    }

    //显示窗口
    fun show(view:View){
        if (view.parent == null){
            mWindowManager.addView(view,mLayoutParams)
        }
    }

    //显示窗口但是窗口属性自定义
    fun show(view: View, layoutParams: WindowManager.LayoutParams){
        if (view.parent == null){
            mWindowManager.addView(view,layoutParams)
        }
    }

    //隐藏视图
    fun hide(view: View){
        //不等于空说明在显示
        if (view.parent != null){
            mWindowManager.removeView(view)
        }
    }

    //修改窗口
    fun update(view: View,layoutParams: WindowManager.LayoutParams){
        mWindowManager.updateViewLayout(view, layoutParams)
    }
}